<template>
    <div class="content">

        <div class="pic">
            <van-image width="10rem" fit="contain" :src="user" alt="" />
        </div>

        <main class="main">
            <p class="title" v-if="allData?.title">{{ allData?.title }}</p>
            <article class="article">
                <p>尊敬的先生/女士:</p>
                <div class="book" v-if="allData?.description">
                    {{ allData?.description }}
                </div>
            </article>
            <!-- <div class="obj" v-if="allData?.questions.length">
                <p class="answer_title">本次共 {{ allData?.questions.length }}题，请填写。</p>
            </div> -->

            <div class="test" v-for="v, k in allData?.questions" :key="v.id">
                <div class="single" v-if="v.topic_type == 1 && v.display == '1'">
                    <div>
                        <div class="single_title"> <span class="require" v-if="v.is_required == 1">*</span>{{
                v.topic_name }}
                        </div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <div style="padding-left: 30px;">
                            <van-radio-group v-model="v.checkOption" v-for="value, key in v.options" shape="dot">
                                <van-radio :name="value.options_id" style="margin-bottom: 10px;"
                                    @click="singleSelect(v, v.id, value.next)">{{ value.options_name
                                    }}</van-radio>
                            </van-radio-group>
                        </div>
                        <van-divider
                            :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="mutl">
                    <div v-if="v.topic_type == 3 && v.display == '1'">
                        <div class="mutl_title"> <span class="require" v-if="v.is_required == 1">*</span>{{ v.topic_name
                            }}
                        </div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <div style="padding-left: 30px;">
                            <van-checkbox-group v-model="v.checkOption" v-for="value, key in v.options">
                                <van-checkbox :name="value.options_id" shape="square" style="margin-bottom: 10px;"
                                    @click="mutleSelect(v.id, value.next)">{{ value.options_name
                                    }}</van-checkbox>
                            </van-checkbox-group>
                        </div>
                        <van-divider
                            :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="single_text">
                    <div v-if="v.topic_type == 2">
                        <div class="single_text_title"> <span class="require" v-if="v.is_required == 1">*</span>{{
                v.topic_name }}</div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <van-cell-group inset>
                            <van-field class="single_border" v-model="v.answer_text" placeholder="请输入内容" />
                        </van-cell-group>
                        <van-divider
                            :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '-2px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="mutl_text">
                    <div v-if="v.topic_type == 4">
                        <div class="leave">
                            <div class="leave_title"> <span class="require" v-if="v.is_required == 1">*</span>{{
                v.topic_name }}
                            </div>
                            <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                            <div class="leave_message">
                                <van-cell-group inset>
                                    <van-field class="mutl_border" v-model="v.answer_text" rows="6" clearable autosize
                                        type="textarea" maxlength="500" placeholder="请输入内容" show-word-limit />
                                </van-cell-group>
                            </div>
                        </div>
                        <van-divider
                            :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '30px auto', }">
                        </van-divider>
                    </div>
                </div>
            </div>
        </main>

        <div class="submit"><van-button type="primary" size="large" @click="throttle(submit)">提交</van-button></div>
    </div>
</template>

<script setup lang="ts">
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { ref } from 'vue'
import { throttle } from '@/util/index'
import user from '@/assets/images/user.jpg'
import { userPost, wenjuanDetails, linkStatus, linkCount } from '@/api/index'
import { POSTmyData, getData } from '@/api/index1'
// import mockJson from './mockJson'
const route = useRoute()
const router = useRouter()
// const leaveMessage = ref('')
// const muti = ref('')
// const singeVlaue = ref('')
// const radio = ref('1');
// const checkbox = ref(['a']);

const reswenjuanDetails = ref()
const text = ref()
const wenjuanxiangqing = async (id) => {
    let res = await wenjuanDetails(id)
    if (res.code == 500) {
        //  showToast('无法获取当前问卷，请刷新后重试')
        reswenjuanDetails.value = []
        router.push({ name: 'notice_fail' })
        return false
    }
    reswenjuanDetails.value = res.data
    text.value = res.data.hcemTemplatTopic
    text.value.map(v => {
        v.scoreInfo = JSON.parse(v.scoreInfo)
        if (v.topicType == 3) {
            v.scoreInfo.forEach((value) => {
                value['myScore'] = []
            })
        } else {
            v.scoreInfo.forEach((value) => {
                value['myScore'] = ''
            })
        }
        // console.log(v);
        return v
    });
    // reswenjuanDetails.value = res
    // return reswenjuanDetails
}
const init = async () => {
    // let id = route.query.id
    // let isEffective = route.query.linkId || ''
    // console.log(route.query.id);

    // if(isEffective){
    //     const res = await linkStatus(isEffective)
    //     if(res.code !==200){  //链接失效直接跳走
    //         router.push({ name: 'notice_fail' })
    //     }else{  //计数
    //         const count = await linkCount(isEffective)

    //     }
    // }else{
    //     showToast('无链接ID，请重新生成链接') 

    // }
    // wenjuanxiangqing(id)
    mockData(123)
}

let allData = ref<Data>()
async function mockData(id: string | number) {
    const temp_id = route.query.template_id
    if (temp_id) {
        let res = await getData(temp_id.toString())
        allData.value = res.data
        window.document.title = allData.value.title
        localStorage.setItem('title',allData.value.title );
        allData.value?.questions.forEach(v => {
            if (v.topic_type == 1) { // 1单选传ID
                v['checkOption'] = ref('')
            }
            if (v.topic_type == 3) { // 3多选传ID
                v['checkOption'] = ref([])
            }
            if ([2, 4].includes(v.topic_type)) v['answer_text'] = ''  // 2填空 4多行填空传文本
        });
    } else {
        showToast('问卷ID不存在，请刷新后重试')
    }

    //console.log();
    // console.log(respone.data);
}

init()
//单选结果赋值

const singleSelect = (question, id: string | number, next: { id: string | number, type: number }) => {
    // console.log(question,id, next);
    allData.value?.questions.forEach(v => {
        //console.log(v.id, next?.id);
        if (next?.id && next.id == v.id) {  //有next值，直接显示
            v.display = "1"
        }
        if (next == null && id == question.id) {   //没有next值，选择当前题目后，找到有next值的题目，隐藏
            let hiddenId = question.options.find(opt => (opt.next !== null))
            // console.log();
            hiddenId && Object.values(allData.value.questions).forEach(question => {
                if (question.id == hiddenId.next.id) {
                    question.display = '0'
                }
            })
        }
    })

    // text.value[k].scoreInfo.forEach((v) => {
    //     v.myScore = ''
    //     v.flag = false
    // })
    // text.value[k].scoreInfo[key].myScore = params
    // text.value[k].scoreInfo[key].flag = true
}

let startTime: number = Date.now();
const formateSeconds = (endTime: number): string => {  //秒转分钟和小时
    let secondTime: number = parseInt(endTime)//将传入的秒的值转化为Number
    let min = 0// 初始化分
    let h = 0// 初始化小时
    let result = ''
    if (secondTime >= 60) {//如果秒数大于等于60，将秒数转换成整数
        min = parseInt(secondTime / 60)//获取分钟，除以60取整数，得到整数分钟
        secondTime = parseInt(secondTime % 60)//获取秒数，秒数取佘，得到整数秒数
        if (min >= 60) {//如果分钟大于等于60，将分钟转换成小时
            h = parseInt(min / 60)//获取小时，获取分钟除以60，得到整数小时
            min = parseInt(min % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
        }
    }
    if (h) {
        result = `${h.toString().padStart(2, '0')}时:${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else if (min) {
        result = `${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else {
        result = `${secondTime.toString().padStart(2, '0')}秒`
    }
    return result
}

//多选结果赋值
const mutleSelect = (id: string | number, next: { id: string | number, type: number }) => {
    //console.log(id, next);
    allData.value?.questions.forEach(v => {
        //console.log(v.id, next.id);
        if (next?.id && next.id == v.id) {
            v.display == "1" ? v.display = "0" : v.display = "1"  //多选可以用三元，但是多选不能用
        }
    })
    // if (text.value[k].scoreInfo[key].flag) {
    //     text.value[k].scoreInfo[key].flag = false
    // } else {
    //     text.value[k].scoreInfo[key].flag = true
    // }
}
const userOptionList = ref<questionPost[]>([])
const submit = async () => {
    userOptionList.value = []
    const questions = Object.values(allData.value!.questions)
    questions && questions.map((v) => {
        if (v.is_required == 1 && [1, 3].includes(v.topic_type)) {  //校验单选和多选
            if (v.checkOption.length == 0) {
                showToast(v.topic_name + '，请选择一个选项')
                return
            }
        }
        if (v.is_required == 1 && [2, 4].includes(v.topic_type)) {  //校验多行和单行文本
            if (v?.answer_text?.length == 0) {
                showToast(v.topic_name + '，请选择一个选项')
                return
            }
        }

        if (v.topic_type == 1) {  //单选
            userOptionList.value.push({ "questionid": v.id.toString(), "answer_text": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.toString() })
        }
        if (v.topic_type == 3) {  //多选
            userOptionList.value.push({ "questionid": v.id.toString(), "answer_text": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.join() })
        }
        if ([2, 4].includes(v.topic_type)) {  //单行文本和多行文本
            userOptionList.value.push({ "questionid": v.id.toString(), "answer_text": v.answer_text!, "question_type": v.topic_type.toString(), "option_id": '' })
        }
        // console.log(userOptionList.value);
        // userOptionList.value.push()
    })
    //  console.log(555,questions);
    postData(userOptionList.value)
}

// async function postData(params:myPost){
//     const url = 'http://192.168.2.93:8080/hcem/user/submitsurvey'
//     const options = {
//         method: 'POST',
//         headers: {
//           'Content-Type': 'application/json', // 如果发送JSON数据
//           // 或者如果是表单数据：
//           // 'Content-Type': 'application/x-www-form-urlencoded'
//         },
//         body: JSON.stringify(params), // 如果是JSON格式
//         // 或者如果是表单数据：
//         // body: new URLSearchParams(formData).toString()
//       };
//     let res = await fetch(url, options)
//     let data = await res.json()
//     console.log(data);

// }

async function postData(params: questionPost[]) {
    let source = { "source": "1" }
    let template_id = { "template_id": allData.value?.template_id.toString() }
    let data = { questions: params, ...source, ...template_id }
    let res = await POSTmyData(data)
    // console.log(res,111);

}


const isPass = () => {
    let opt = text.value.map((v) => {
        //   console.log(v);
        const mytopicType = Number(v.topicType)
        if (v.isRequired == 1 && [1, 3].includes(mytopicType)) {
            let reslut = v.scoreInfo.findIndex(values => {
                return values.flag == true
            })
            if (reslut == -1) {
                showToast(`${v.topicName}，请选择一个选项`)
                return false
            } else {
                return true
            }
        } else if (v.isRequired == 1 && [2, 4].includes(mytopicType)) {
            if (v.scoreInfo == '') {
                showToast(`请填写${v.topicName}`)
                return false
            } else {
                return true
            }
        } else {
            return true
        }
    })
    if (opt.includes(false)) {
        return false
    } else {
        return true
    }
}

</script>
<style>
.van-radio{
    margin-bottom: 30px;
}
</style>
<style scoped lang="scss">
.content {
    // padding-top: 48px;

    .pic {
        position: relative;
        z-index: 1;
    }

    .main {
        position: relative;
        z-index: 2;
        margin-top: -25px;
        background-color: #fff;
        // height: 100vh;
        border-radius: 30px;

        .title {
            padding: 18px 44px 15px 44px;
            margin: 0 auto;
            text-align: center;
            width: 287px;
            font-size: 22px;
            font-weight: 500;
            color: #3D3D3D;
            line-height: 32px;
        }

        .article {
            margin: 0 auto;
            width: 337px;
            // height: 102px;
            font-size: 14px;
            font-family: Source Han Sans CN-Regular, Source Han Sans CN;
            font-weight: 400;
            color: #999999;
            line-height: 17px;

            .book {
                margin-top: 20px;
                margin-bottom: 20px;
                text-indent: 2em;
            }
        }

        .obj {

            .answer_title {
                margin: 30px 0 28px 20px;
                font-size: 14px;
                font-weight: 400;
                color: #999999;
                line-height: 20px;
            }
        }

        .require {
            color: red;
            padding-right: 5px;
            line-height: 15px;
        }

        .test {
            margin-left: 10px;

            .secondTitle {
                padding-left: 20px;
                padding-bottom: 10px;
                color: #999999;
                font-size: 14px;
            }

            .single {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;
                padding-top: 15px;

                .single_title {
                    padding-left: 20px;
                    padding-bottom: 5px;
                }
            }

            .mutl {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;

                .mutl_title {
                    padding-left: 20px;
                    padding-bottom: 10px;
                }
            }

            .single_text {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;

                .single_text_title {
                    padding-left: 20px;
                    // :deep .van-cell {
                    //     border: 1px solid #ccc !important;
                    // }
                }

                .single_border {
                    :deep .van-cell {
                        border: none;
                    }
                }


            }

            .mutl_text {
                .leave {

                    .leave_title {
                        font-size: 14px;
                        font-weight: 400;
                        color: black;
                        line-height: 17px;
                        padding-left: 20px;
                        padding-bottom: 5px;
                    }

                    .leave_message {
                        margin-right: 25px;
                        //  padding-bottom: 5px;

                        .mutl_border {
                            border: 1px solid #ccc !important;
                        }
                    }
                }
            }
        }
    }



    .submit {
        margin: 0 auto;
        width: 85%;
        padding: 20px 0;
    }
}

::v-deep(.van-cell-group--inset) {
    border-radius: 2px !important;
}
</style>